<?php

    class XMLHelper
    {
        public static function CreateObjectFromDOMNode( XPathHelper $xpath, DOMNode $node, $deep = false )
        {
            $obj = array();
            $childs = $xpath->GetNodes("*", $node);
            foreach ( $childs as $child )
            {
                $child instanceof DOMNode;
                $nodeName = $child->nodeName;
                $key = self::NormalizeName($nodeName);

                $subNodes = null;
                if ( $deep && $child->hasChildNodes() )
                {
                    $subNodes = $xpath->GetNodes("*", $child);
                }

                $value = null;
                if ( $deep && $subNodes )
                {
                    $value = self::CreateObjectFromDOMNode( $xpath, $child, $deep );
                }
                else
                {
                    $value = $xpath->GetText("", $child);
                }

                if ( isset( $obj[ $key ] ) )
                {
                    $values = (array) $obj[ $key ];
                    $values[] = $value;
                    $obj[ $key ] = $values;
                }
                else
                {
                    $obj[ $key ] = $value;
                }
            }
            return (object) $obj;
        }

        /**
         * Returns attribute value, if it's set, else returns empty string.
         *
         * @param DOMDocument $node
         * @param string $attr
         * @return string
         */
        public static function GetAttribute( $node, $attr )
        {
            return ( $node->hasAttribute( $attr ) ) ? $node->getAttribute( $attr ) : "";
        }

        private static function NormalizeName( $name )
        {
            $name = trim( str_replace('-', '_', "$name") );
            return $name;
        }
    }

?>
